<template>
  <div>
    <slot></slot>
    <div ref="loadingTarget" class="h-6 py-4">
      <m-svg-icon
        v-show="loading"
        class="w-4 h-4 mx-auto animate-spin"
        name="infinite-load"
        color="zinc-200"
      ></m-svg-icon>
      <p v-if="isFinished" class="text-center text-base text-zinc-400">
        没有更多了
      </p>
    </div>
  </div>
</template>
<script setup>
import { useVModel, useIntersectionObserver } from '@vueuse/core'
import { ref, watch } from 'vue'
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: true
  },
  isFinished: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:modelValue', 'onLoad'])
const loading = useVModel(props, 'modelValue')
const loadingTarget = ref(null)
const intersecting = ref(false)
useIntersectionObserver(
  loadingTarget,
  ([{ isIntersecting }], obseverElement) => {
    intersecting.value = isIntersecting
    emitLoad()
  }
)
const emitLoad = () => {
  if (intersecting.value && !props.isFinished && !loading.value) {
    loading.value = true
    emits('onLoad')
  }
}
watch(loading, (val) => {
  setTimeout(() => {
    emitLoad()
  }, 100)
})
</script>
